package com.cn.goodsadmin.dao.impl;

import com.cn.goodsadmin.dao.BaseDao;
import com.cn.goodsadmin.dao.IAppDao;
import com.cn.goodsadmin.po.App;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

@Repository("AppDaoImpl")
public class AppDaoImpl extends BaseDao<App> implements IAppDao {
    public App findAppByAppId(final String appId) throws Exception {
        final StringBuilder builder = new StringBuilder();
        builder.append("from App a where a.cAppid=?0");
        return getHibernateTemplate().execute(new HibernateCallback<App>() {
            public App doInHibernate(Session session) throws HibernateException {
                Query query = session.createQuery(builder.toString());
                query.setCacheable(true);
                query.setParameter(0, appId);
                List<App> apps = query.list();
                if (apps != null && apps.size() > 0) {
                    return apps.get(0);
                }
                return null;
            }
        });
    }

    public List<App> findAllApp() throws Exception {
        StringBuilder builder=new StringBuilder();
        builder.append("from App a where a.cIsEnable=1");
        return find(builder.toString());
    }

    public App findAppById(int id) throws Exception {
        return get(App.class,id);
    }

    public App findAppByNameAndPass(final String name, final String pass) throws Exception {
        final StringBuilder builder=new StringBuilder();
        builder.append("from App app where app.cAppname=?0");
        builder.append(" and app.cApppass=?1");
        builder.append(" and app.cIsEnable=1");
        return getHibernateTemplate().execute(new HibernateCallback<App>() {
            public App doInHibernate(Session session) throws HibernateException {
                Query query=session.createQuery(builder.toString());
                query.setParameter(0,name);
                query.setParameter(1,pass);
                List<App> apps=query.list();
                if(apps!=null&&apps.size()>0){
                    return apps.get(0);
                }
                return null;
            }
        });
    }

    @Override
    public void updateAppData(String sorimg, String orcode, String soreName,int appid) {
        StringBuilder builder=new StringBuilder();
        builder.append("update App a set a.cOrcode='"+orcode+"'");
        builder.append("  ,a.cSoreName='"+soreName+"'");
        builder.append("  ,a.cSoreImg='"+sorimg+"'");
        builder.append("  where a.cId="+appid);
        getHibernateTemplate().bulkUpdate(builder.toString());
    }
}
